package dispatcher;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import dao.Filter;
import dao.ObjectDao;

import services.PollService;
import services.UserService;
import utils.MyBase64;
import utils.Utils;

import business.Company;
import business.CompanyCampaign;
import business.CompanyPoll;
import business.Country;
import business.CoverDefinition;
import business.Indicator;
import business.IndustrialMP;
import business.IndustrialProduct;
import business.Local;
import business.LocalMenu;
import business.LocalType;
import business.MiningItem;
import business.PollValue;
import business.UserCompanyCampaign;

public class GetPollValues extends HttpServlet{
	/**
	 * 
	 */
	static Logger log = Logger.getLogger(GetPollValues.class);
	
	private static final long serialVersionUID = 1L;
	private String lockCover = null;
	private Long companyCampaignID = null;
	private PollService pollService;
	public GetPollValues()
	{
		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	private void setValues(Long idEncuesta, List<PollValue> valorEncuestaList,
			Local local, CompanyCampaign companyCampaign, HttpServletRequest request)
	{
		List<CoverDefinition> coverDefinitionsList = pollService.getCoverDefinitionsByPoll(idEncuesta);
		boolean flag = false;
		if(coverDefinitionsList != null && coverDefinitionsList.size() > 0)
		{
			StringBuilder strBuild = new StringBuilder();
			for(CoverDefinition coverDef : coverDefinitionsList)
			{
				//Generalmente todos los valores que se traen son para caratulas y no se pueden editar, en este caso controlo que si es un dato especial no lo agregue al lockcover para que se pueda editar
				if(!(coverDef.getPollID().equals(PollService.POLL_EPN_ID) && coverDef.getField().equals(Company.ATT_FECHA_CIERRE)))
				{
					strBuild.append(coverDef.getCode());
					strBuild.append("|");
				}
			}
			if(strBuild.length() > 0)
			{
				lockCover = strBuild.toString().substring(0, strBuild.toString().length() - 1);	
			}
		}
										
		for(PollValue valorEncuesta : valorEncuestaList)
		{			
			flag = false;
			if(coverDefinitionsList.size() > 0)
			{
				for(CoverDefinition coverDef : coverDefinitionsList)
				{
					if(valorEncuesta.getPollDefinition()
							.getCode().equals(coverDef.getCode()))
					{
						String attName = "ATT_" + coverDef.getCode();
						
						if(coverDef.getTable().equals(PollService.LOCAL_TABLE))
						{
							request.setAttribute(attName,local.getAttribute(coverDef.getField()));
						}
						else if(coverDef.getTable().equals(PollService.COMPANY_TABLE))
						{
							request.setAttribute(attName,companyCampaign.getCompany().getAttribute(coverDef.getField()));
						}
						else if(coverDef.getTable().equals(PollService.CAMPANA_VALUES))
						{
							request.setAttribute(attName,companyCampaign.getCampaign().getYear());
						}
						else
						{
							request.setAttribute(attName,valorEncuesta.getValue());
						}
						
						flag = true;
						break;
					}
				}
				if(!flag)
				{					
					String attName = "ATT_" + valorEncuesta.getPollDefinition().getCode();
					String valorOriginal = valorEncuesta.getValue();
					if(valorOriginal != null)
					{
						if(valorEncuesta.getPollDefinition().isFormat())
						{
							request.setAttribute(attName, Utils.generateValue(valorOriginal.replace(".", ",").toString()));	
						}
						else
						{
							request.setAttribute(attName, valorOriginal.replace(".", ","));	
						}
					}
				}
			}
			else
			{
				String attName = "ATT_" + valorEncuesta.getPollDefinition().getCode();
				
				String valorOriginal = valorEncuesta.getValue();
				if(valorOriginal != null)
				{
					if(valorEncuesta.getPollDefinition().isFormat())
					{
						request.setAttribute(attName, Utils.generateValue(valorOriginal.replace(".", ",").toString()));
					}
					else
					{
						request.setAttribute(attName, valorOriginal.replace(".", ","));	
					}
				}
			}
			
		}
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		log.info("Se cargo una encuesta");
		
		Properties msge = Utils.getProperties("resource/messages_es.properties");
		HttpSession session = request.getSession(true);
		Object sessionUserID = session.getAttribute("userID");
		Object sessionUserRole = session.getAttribute("userRole");
		Object sessionCompanyStatus = session.getAttribute("companyStatus");
		pollService = new PollService();
		
		if(sessionUserID == null || sessionUserID.toString().trim().length() == 0)
		{
			response.sendRedirect("./login?option=" + MyBase64.encode(Login.NO_SESSION.getBytes()));
		}
		else
		{
			response.setContentType("text/html;charset=ISO-8859-1");
			response.setCharacterEncoding("UTF-8");
			String strParams = request.getParameter("params");			
			if (Utils.controlString(strParams))
			{
				strParams = MyBase64.decodeToString(strParams);
				String[] splitParams = strParams.split("[|]");
				
				if (splitParams != null && splitParams.length == 3
						&& Utils.controlString(splitParams[0])
						&& Utils.controlString(splitParams[1])
						&& Utils.controlString(splitParams[2])) {
					
					lockCover = new String();
					Long userID = (Long) sessionUserID;
					Long companyStatusID = (Long) sessionCompanyStatus;
					companyCampaignID = Long.valueOf(splitParams[0]);
					Long pollID = Long.valueOf(splitParams[1]);
					Long localID = Long.valueOf(splitParams[2]);
					
					List<PollValue> valorEncuestaList = new PollService()
							.getPollValues(pollID, companyCampaignID,localID);
					
					if(valorEncuestaList != null && valorEncuestaList.size() > 0)
					{
						//BUSCO EL PERMISO
						UserService userService = new UserService();
						UserCompanyCampaign userCompanyCampaign = userService.getUserCompanyCampaignByUserIDAndCompanyCampaignID(userID, companyCampaignID);
						
						CompanyPoll encuestaEmpresa = valorEncuestaList.get(0).getCompanyPoll();
							StringBuilder page = new StringBuilder();
							page.append("/polls/poll_");
							page.append(encuestaEmpresa.getPoll().getCode().toLowerCase());
							page.append("/poll.jsp");

							String enabledButtons = userService.getFormButtonsStringByRoleAndPollStatus(sessionUserRole.toString(), companyStatusID);

							request.setAttribute("ATT_COMPANY_CAMPAIGN_ID", companyCampaignID);
							request.setAttribute("ATT_ENABLED_BUTTONS", enabledButtons);
							request.setAttribute("ATT_POLL_ID", pollID);
							request.setAttribute("ATT_LOCAL", localID);
							request.setAttribute("ATT_STATUS", encuestaEmpresa.getFormStatus().getId());
							request.setAttribute("ATT_PERMISSION", userCompanyCampaign.getPermission().getId());
							request.setAttribute("ATT_USER_TYPE",sessionUserRole.toString());
							CompanyCampaign companyCampaign = encuestaEmpresa.getCompanyCampaign();							
							int year = companyCampaign.getCampaign().getYear().intValue();
							int previousYear = year - 1;
							request.setAttribute("ATT_CAMPAIGN_YEAR",year);
							request.setAttribute("ATT_CAMPAIGN_PREVIOUS_YEAR",previousYear);
							Local local = encuestaEmpresa.getLocal();
							String valor="";
							if(local != null){
								valor=local.getClanae().toString();}
							
							setValues(pollID,valorEncuestaList,local,companyCampaign,request);
							
							if(pollID.equals(PollService.POLL_EI_ID))
							{
								List<LocalMenu> localesEmpresa = pollService.getMenuLocalsByCompanyFilterByType(companyCampaignID,LocalType.LOCALS_PR_STR);
								request.setAttribute("locals", localesEmpresa);
								
								for(LocalMenu lm : localesEmpresa)
								{
									List<Indicator> indicators = pollService.getIndicators(companyCampaignID, lm.getLocal().getId(),PollService.INDICATORS_WITH_TRANSFERENCE);
									for(Indicator indicator : indicators)
									{
										request.setAttribute(indicator.getDefinition().replace(":", "_").replace("~", "_").replace(".", "_").replace(" ", "_").replace("/", "_") + "_" + lm.getLocal().getId(), indicator.getValue());
									}
								}
								
								localesEmpresa = pollService.getMenuLocalsByCompanyFilterByType(companyCampaignID,LocalType.LOCALS_AC_UC_STR);
								request.setAttribute("locals2", localesEmpresa);
								for(LocalMenu lm : localesEmpresa)
								{
									List<Indicator> indicators = pollService.getIndicators(companyCampaignID, lm.getLocal().getId(),PollService.INDICATORS_WITH_TRANSFERENCE);
									for(Indicator indicator : indicators)
									{
										request.setAttribute(indicator.getDefinition().replace(":", "_").replace("~", "_").replace(".", "_").replace(" ", "_").replace("/", "_") + "_" + lm.getLocal().getId(), indicator.getValue());
									}
								}
							}
							
							if(pollID.equals(PollService.POLL_EIC_ID) || pollID.equals(PollService.POLL_EIMC_ID))
							{
								List<LocalMenu> localesEmpresa = pollService.getMenuLocalsByCompanyFilterByType(companyCampaignID,LocalType.LOCALS_PR_STR);
								request.setAttribute("locals", localesEmpresa);
								
								for(LocalMenu lm : localesEmpresa)
								{
									List<Indicator> indicators = pollService.getIndicators(companyCampaignID, lm.getLocal().getId(),PollService.INDICATORS_REGIONALIZED);
									for(Indicator indicator : indicators)
									{
										request.setAttribute(indicator.getDefinition().replace(":", "_").replace("~", "_").replace(".", "_").replace(" ", "_").replace("/", "_") + "_" + lm.getLocal().getId(), indicator.getValue());
									}
								}
								
								localesEmpresa = pollService.getMenuLocalsByCompanyFilterByType(companyCampaignID,LocalType.LOCALS_AC_UC_STR);
								request.setAttribute("locals2", localesEmpresa);
								for(LocalMenu lm : localesEmpresa)
								{
									List<Indicator> indicators = pollService.getIndicators(companyCampaignID, lm.getLocal().getId(),PollService.INDICATORS_REGIONALIZED);
									for(Indicator indicator : indicators)
									{
										request.setAttribute(indicator.getDefinition().replace(":", "_").replace("~", "_").replace(".", "_").replace(" ", "_").replace("/", "_") + "_" + lm.getLocal().getId(), indicator.getValue());
									}
								}
							}
							
							if(pollID == PollService.POLL_E_ID)
							{
								//SETEO LA LISTA DE INPUTS QUE DEBEN ESTAR BLOQUEADOS
								StringBuilder strBuilder = new StringBuilder();
								List<String> lockedList = pollService.getLockedFieldsFormE();
								for(String xlew : lockedList)
								{
									strBuilder.append(xlew);
									strBuilder.append("|");
								}
								if(strBuilder.length() > 0)
								{
									lockCover += "|" + strBuilder.toString().substring(0, strBuilder.length() - 1);	
								}
								List<Country> countries = pollService.getCountries();
								request.setAttribute("ATT_COUNTRIES", countries);
								
								List<String> formLENCTValues = pollService.getVariablesFormL(companyCampaignID, Local.VAR_L_EN_CT);
								Long formLENCTValue = Utils.sumVariables(formLENCTValues);
								List<String> formLENSTValues = pollService.getVariablesFormL(companyCampaignID, Local.VAR_L_EN_ST);
								Long formLENSTValue = Utils.sumVariables(formLENSTValues);								
								
								request.setAttribute("ATT_VAR_L_EN_CT", formLENCTValue);
								request.setAttribute("ATT_VAR_L_EN_ST", formLENSTValue);
								
							}
							else if((pollID == PollService.POLL_LR_ID) || (pollID == PollService.POLL_L_ID))
							{
								List<Filter> filters = new ArrayList<Filter>();
								Filter filter = new Filter(Filter.NUMERIC_FILTER, "LOC.ID_LOCAL", Filter.EQUAL_OPERATOR,localID,true);
								filters.add(filter);
								local = new ObjectDao().getLocals(filters, ObjectDao.AND_OPERATOR).get(0);
								request.setAttribute("ATT_LOCAL_TYPE", local.getLocalType().getLocalType());
								
								
								String formE7121Value = pollService.getVariableFormE(companyCampaignID, Company.VAR_7_1_2_1);								
								
								if (pollID == PollService.POLL_L_ID)
								{
									String formL11401Value = pollService.getVariableFormL(companyCampaignID, Local.VAR_L_1_14_0_1, localID);
									List<String> formL11401Values = pollService.getVariablesFormL(companyCampaignID, Local.VAR_L_1_14_0_1);
									if (formL11401Values.isEmpty())
									{
										formL11401Values.add("0");
									}
									boolean valueIsMayor = Utils.valueIsMayorThanList(formL11401Value, formL11401Values);
									
									if(valueIsMayor)
									{
										request.setAttribute("ATT_VAR_E_7_1_2_1", formE7121Value);
									}
									else
									{
										request.setAttribute("ATT_VAR_E_7_1_2_1", "0");
									}
									
								}
								else
								{
									String formLR11401Value = pollService.getVariableFormL(companyCampaignID, Local.VAR_LR_1_14_0_1, localID);
									List<String> formLR11401Values = pollService.getVariablesFormL(companyCampaignID, Local.VAR_LR_1_14_0_1);
								
									boolean valueIsMayor = Utils.valueIsMayorThanList(formLR11401Value, formLR11401Values);
									
									if(valueIsMayor)
									{
										request.setAttribute("ATT_VAR_E_7_1_2_1", formE7121Value);
									}
									else
									{
										request.setAttribute("ATT_VAR_E_7_1_2_1", "0");
									}
								}								
								
							}							
							else if(pollID == PollService.POLL_PB_ID)
							{
								List<Country> countries = pollService.getCountries();
								request.setAttribute("ATT_COUNTRIES", countries);
							}
							else if(pollID == PollService.POLL_ME_ID || pollID == PollService.POLL_MPB_ID)
							{
								List<MiningItem> miningItems = pollService.getMiningItems();
								request.setAttribute("ATT_MINING_ITEMS", miningItems);
							}
							else if(pollID == PollService.POLL_ACPI_ID)
							{
								List<IndustrialProduct> industrialProducts = pollService.getIndustrialProducts(valor);
								request.setAttribute("ATT_INDUSTRIAL_PRODUCTS", industrialProducts);
								
								List<IndustrialMP> industrialMP = pollService.getIndustrialMP(valor);
								request.setAttribute("ATT_INDUSTRIAL_MPRIMA", industrialMP);
							}
							
							if(lockCover != null && lockCover.trim().length() > 0)
							{
								request.setAttribute("ATT_LOCKED_LIST", lockCover);
							}
							else
							{
								request.setAttribute("ATT_LOCKED_LIST", "");
							}
							RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page.toString());
							dispatcher.forward(request, response);
					}
					else
					{
						String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
						msge.getProperty("getPoll.load.ValuesNotGenerated"));
						response.sendRedirect(page);
					}
				}
				else
				{				
					String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
							msge.getProperty("getPoll.load.ParamsNotValid"));
					response.sendRedirect(page);
				}
			}
			else
			{
				String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
						msge.getProperty("getPoll.load.ParamsNotValid"));
				response.sendRedirect(page);
			}
		}
		
//		//Usuario Editor
//		else if(sessionUserTypeID == UserService.USUARIO_EDITOR_ID)
//		{
//			String strParams = request.getParameter("params");
//			
//			if (Utils.controlString(strParams))
//			{
//				strParams = MyBase64.decodeToString(strParams);
//				String[] splitParams = strParams.split("[|]");
//				
//				if (splitParams != null && splitParams.length == 3
//						&& Utils.controlString(splitParams[0])
//						&& Utils.controlString(splitParams[1])
//						&& Utils.controlString(splitParams[2])) {
//					
//					Long companyCampaignID = Long.valueOf(splitParams[0]);
//					Long pollID = Long.valueOf(splitParams[1]);
//					String localStr = splitParams[2];
//					
//					List<PollValue> valorEncuestaList = new PollService()
//							.getPollValues(pollID, companyCampaignID,localStr);
//					
//					if(valorEncuestaList != null && valorEncuestaList.size() > 0)
//					{
//						CompanyPoll encuestaEmpresa = valorEncuestaList.get(0).getCompanyPoll();
//							StringBuilder page = new StringBuilder();
//							page.append("/polls/poll_");
//							page.append(encuestaEmpresa.getPoll().getCode().toLowerCase());
//							page.append("/poll.jsp");
//							
//							request.setAttribute("ATT_COMPANY_CAMPAIGN_ID", companyCampaignID);
//							request.setAttribute("ATT_POLL_ID", pollID);
//							request.setAttribute("ATT_LOCAL", localStr);
//							request.setAttribute("ATT_STATUS", encuestaEmpresa.getFormStatus().getId());
//							request.setAttribute("ATT_USER_TYPE",sessionUserTypeID.toString());
//							CompanyCampaign companyCampaign = encuestaEmpresa.getCompanyCampaign();
//							Local local = encuestaEmpresa.getLocal();
//							
//							if(pollID == PollService.ENCUESTA_E_ID)
//							{
//								//SETEO LA LISTA DE INPUTS QUE DEBEN ESTAR BLOQUEADOS
//								StringBuilder strBuilder = new StringBuilder();
//								List<String> lockedList = new PollService().getLockedFieldsFormE();
//								for(String xlew : lockedList)
//								{
//									strBuilder.append(xlew);
//									strBuilder.append("|");
//								}
//								String attLockedList = strBuilder.toString().substring(0, strBuilder.length() - 1);
//								request.setAttribute("ATT_LOCKED_LIST", attLockedList);
//							}
//							else if(lockCover != null && lockCover.trim().length() > 0)
//							{
//								
//							}
//							
//							setValues(pollID,valorEncuestaList,local,companyCampaign,request);
//							
//							RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page.toString());
//							dispatcher.forward(request, response);
//					}
//					else
//					{
//						String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
//						msge.getProperty("getPoll.load.ValuesNotGenerated"));
//						response.sendRedirect(page);
//					}
//				}
//				else
//				{				
//					String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
//							msge.getProperty("getPoll.load.ParamsNotValid"));
//					response.sendRedirect(page);
//				}
//			}
//			else
//			{
//				String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
//						msge.getProperty("getPoll.load.ParamsNotValid"));
//				response.sendRedirect(page);
//			}
//		}
//		//Usuario Revisor/Aprobador
//		else if(sessionUserTypeID == UserService.USUARIO_REVISOR_ID)
//		{
//			String strParams = request.getParameter("params");
//			
//			if (Utils.controlString(strParams))
//			{
//				strParams = MyBase64.decodeToString(strParams);
//				String[] splitParams = strParams.split("[|]");
//				
//				if (splitParams != null && splitParams.length == 3
//						&& Utils.controlString(splitParams[0])
//						&& Utils.controlString(splitParams[1])
//						&& Utils.controlString(splitParams[2])) {
//					
//					Long companyCampaignID = Long.valueOf(splitParams[0]);
//					Long idEncuesta = Long.valueOf(splitParams[1]);
//					String localStr = splitParams[2];
//					
//					//TODO ACA DEBERIA CHEQUEAR QUE TENGA PERMISOS!
//					
//					List<PollValue> valorEncuestaList = new PollService()
//							.getPollValues(idEncuesta,companyCampaignID ,localStr);
//					
//					if(valorEncuestaList != null && valorEncuestaList.size() > 0)
//					{
//						CompanyPoll encuestaEmpresa = valorEncuestaList.get(0).getCompanyPoll();
//							StringBuilder page = new StringBuilder();
//							page.append("/polls/poll_");
//							page.append(encuestaEmpresa.getPoll().getCode().toLowerCase());
//							page.append("/poll.jsp");
//							
//							request.setAttribute("ATT_COMPANY_CAMPAIGN_ID", companyCampaignID);
//							request.setAttribute("ATT_POLL_ID", idEncuesta);
//							request.setAttribute("ATT_LOCAL", localStr);
//							request.setAttribute("ATT_STATUS", encuestaEmpresa.getFormStatus().getId());
//							request.setAttribute("ATT_USER_TYPE",sessionUserTypeID.toString());
//							CompanyCampaign companyCampaign = encuestaEmpresa.getCompanyCampaign();
//							Local local = encuestaEmpresa.getLocal();
//							
//							if(idEncuesta == PollService.ENCUESTA_E_ID)
//							{
//								//SETEO LA LISTA DE INPUTS QUE DEBEN ESTAR BLOQUEADOS
//								StringBuilder strBuilder = new StringBuilder();
//								List<String> lockedList = new PollService().getLockedFieldsFormE();
//								for(String xlew : lockedList)
//								{
//									strBuilder.append(xlew);
//									strBuilder.append("|");
//								}
//								String attLockedList = strBuilder.toString().substring(0, strBuilder.length() - 1);
//								request.setAttribute("ATT_LOCKED_LIST", attLockedList);
//							}
//							
//							setValues(idEncuesta,valorEncuestaList,local,companyCampaign,request);
//							
//							RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page.toString());
//							dispatcher.forward(request, response);
//					}
//					else
//					{
//						String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
//						msge.getProperty("getPoll.load.ValuesNotGenerated"));
//						response.sendRedirect(page);
//					}
//				}
//				else
//				{				
//					String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
//							msge.getProperty("getPoll.load.ParamsNotValid"));
//					response.sendRedirect(page);
//				}
//			}
//			else
//			{
//				String page = Utils.getMessagePage(Utils.MESSAGE_TYPE_ERROR,
//						msge.getProperty("getPoll.load.ParamsNotValid"));
//				response.sendRedirect(page);
//			}
//		}
	}
}
